const sanitizeEnvValue = (value: string | undefined) => value?.trim() ?? '';

export const API_BASE_URL =
  process.env.EXPO_PUBLIC_API_BASE_URL?.replace(/\/+$/, '') ?? 'http://192.168.56.1:9090/api/v1';

export const API_ORIGIN = (() => {
  try {
    const url = new URL(API_BASE_URL);
    const parts = url.pathname.replace(/\/+$/, '').split('/').filter(Boolean);
    if (parts.length > 0) {
      url.pathname = '/';
    }
    return url.toString().replace(/\/+$/, '');
  } catch {
    return API_BASE_URL.replace(/\/?api\/.*/, '').replace(/\/+$/, '');
  }
})();

export function resolveAssetUrl(path: string): string {
  if (!path) return '';
  if (/^https?:\/\//i.test(path)) return path;
  const normalized = path.startsWith('/') ? path : `/${path}`;
  return `${API_ORIGIN}${normalized}`;
}

export const MERCHANT_USERNAME =
  sanitizeEnvValue(process.env.EXPO_PUBLIC_MERCHANT_USERNAME) || '';

export const MERCHANT_PASSWORD =
  sanitizeEnvValue(process.env.EXPO_PUBLIC_MERCHANT_PASSWORD) || '';

export const WECHAT_QR_URL =
  sanitizeEnvValue(process.env.EXPO_PUBLIC_WECHAT_QR_URL) || '';
